# Maintainer: Andrew Crerar <crerar@archlinux.org>
# Maintainer: Christian Rebischke <chris.rebischke@archlinux.org>
# Contributor: Christoph Gysin <christoph.gysin@gmail.com>

pkgname=pulumi
pkgver=3.94.2
pkgrel=1
pkgdesc='Modern Infrastructure as Code'
arch=('loong64' 'x86_64')
url="https://github.com/$pkgname/$pkgname"
license=('Apache')
depends=('glibc')
makedepends=('go')
source=("$pkgname-$pkgver.tar.gz::$url/archive/v$pkgver.tar.gz")
b2sums=('06cc22b7a7ca5f437c0a41af5179a39d2efc66a90e87a372ac6f9deb8e0a925248c9cea11737684ee0e7525b7dbac89c4ee3db01a7a53680d80e42be70f56fcc')
options=('!lto') # disable as soon as LTO problems are resolved

_plugin_dirs=(
  "python/cmd/pulumi-language-python"
  "nodejs/cmd/pulumi-language-nodejs"
  "go/pulumi-language-go"
)

build() {
  cd "${srcdir}/${pkgname}-${pkgver}"

  export CGO_CPPFLAGS="${CPPFLAGS}"
  export CGO_CFLAGS="${CFLAGS}"
  export CGO_CXXFLAGS="${CXXFLAGS}"
  export CGO_LDFLAGS="${LDFLAGS}"
  export GOFLAGS="-buildmode=pie -trimpath -mod=readonly -modcacherw"

  # Build the `pulumi` executable
  cd "${srcdir}/${pkgname}-${pkgver}/pkg"
  go build \
    -ldflags "-X github.com/pulumi/pulumi/pkg/v${pkgver%%.*}/version.Version=${pkgver} -extldflags ${LDFLAGS}" \
    -o "${srcdir}/${pkgname}-${pkgver}/bin/${pkgname}" \
    "./cmd/${pkgname}" \

  # Build the plugins
  cd "${srcdir}/${pkgname}-${pkgver}/sdk"
  for plugin_dir in "${_plugin_dirs[@]}"; do
    plugin_name="${plugin_dir##*/}"
    cwd="${PWD}"
    cd "${plugin_dir}"

    go build \
      -ldflags "-X github.com/pulumi/pulumi/sdk/v${pkgver%%.*}/version.Version=${pkgver} -extldflags ${LDFLAGS}" \
      -o "${srcdir}/${pkgname}-${pkgver}/bin/${plugin_name}" \
      .

    # Add possible executor
    cd ..
    if [ -f "${plugin_name}-exec" ]; then
      cp "${plugin_name}-exec" "${srcdir}/${pkgname}-${pkgver}/bin/"
    fi
    cd "${cwd}"
  done
}

package() {
  cd "${srcdir}/${pkgname}-${pkgver}"

  # Install all executables
  for f in ./bin/*; do
    install -D -m 755 "$f" "${pkgdir}/usr/bin/$(basename $f)"
  done

  # Generate Bash completion
  install -D -m 644 \
    <("${pkgdir}/usr/bin/${pkgname}" gen-completion bash) \
    "${pkgdir}/etc/bash_completion.d/${pkgname}"

  # Generate ZSH completion
  install -D -m 644 \
    <("${pkgdir}/usr/bin/${pkgname}" gen-completion zsh) \
    "${pkgdir}/usr/share/zsh/site-functions/_${pkgname}"

  # Generate Fish completion
  install -D -m 644 \
    <("${pkgdir}/usr/bin/${pkgname}" gen-completion fish) \
    "${pkgdir}/usr/share/fish/completions/${pkgname}.fish"
}

# vim:set ts=2 sw=2 et:
